﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Threading;

namespace LuBrowser
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);
        }

        void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult msgRst = MessageBox.Show("要退出 卤浏览器 吗？", "提示", MessageBoxButton.OKCancel);
            if (msgRst == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
            }
        }

        
        // 将 siteTextBox 的值传递到 WebView 页面中的 site
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            var targetPage = e.Content as Views.WebView;
            if (targetPage != null)
            {
                targetPage.site = SiteTextBox.Text; //site 的参数值  
            }
        }

        
        
    // 计时器，用来设定 popup 的弹窗提示在2秒后自动隐藏
    public void   Timers(){
    timer = new DispatcherTimer() ;
    timer.Tick += new EventHandler(timer_Tick);
    timer.Interval = TimeSpan.FromSeconds(2);
    timer.Start();
 
    }
    DispatcherTimer timer;
    void timer_Tick(object sender, EventArgs e)
    {
        errorPop.IsOpen=false;
        timer.Stop();
    }
    




        private void GoButton_Click(object sender, RoutedEventArgs e)
        {
            webBrowse();
        }

        // siteTextBox 中输入网址，若按下 Enter 键则打开网页
        private void SiteTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                webBrowse();
        }
        

        // 跳转到 WebView Page 方法
        public void webBrowse()
        {
            // 判断用户输入是否正确，给出提示
            // 正则表达式纯复制粘贴，
            Regex regex = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); 
            if (!regex.IsMatch(SiteTextBox.Text.Trim()))
            {
                errorPop.IsOpen = true;
                Timers();
                //errorPop.IsOpen = false;
                
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/WebView.xaml", UriKind.Relative));
            }

        }

       
        

       
    }
}